package tech.tuister.cninfo.download.util;

import com.alibaba.fastjson2.JSON;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;

import java.io.IOException;
import java.io.Serializable;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Slf4j
public class Stocks {

    @Data
    public static class Stock implements Serializable {
        private static final long serialVersionUID = 2235345202862025050L;

        private String code;
        private String pinyin;

        private String category;

        private String orgId;

        private String zwjc;

    }

    static final Map<String, Stock> code2Stock = new HashMap<>();

    static final Map<String, Stock> name2Stock = new HashMap<>();

    static {
        try {
            //每次都下载一遍
            String json = HttpUtils.get("http://www.cninfo.com.cn/new/data/szse_stock.json");
            List<Stock> stocks = JSON.parseObject(json).getList("stockList", Stock.class);
            log.info("Load {} stocks", stocks.size());
            for (Stock stock : stocks) {
                code2Stock.put(stock.getCode(), stock);
                name2Stock.put(stock.getZwjc(), stock);

            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static Stock findStock(String key) {
        if (code2Stock.containsKey(key)) {
            return code2Stock.get(key);
        } else if (name2Stock.containsKey(key)) {
            return name2Stock.get(key);
        }

        for (String name : name2Stock.keySet()) {
            if (name.contains(key)) {
                return name2Stock.get(name);
            }
        }
        return null;
    }

}
